package com.my.drools.util;

import ch.qos.logback.core.util.FileUtil;
import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.XMLWriter;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

/**
 * @Description
 * @Author 36549
 * @Date 2019/7/24
 * @Version V1.0.0
 */
public class CreateDroolsFile {

    public static String createDroolsFile(String tip,String rulename) throws IOException {
        StringBuilder stringBuilder =new StringBuilder();
        stringBuilder.append("package lesson1\r\n");
        stringBuilder.append("import com.my.drools.entity.Account\r\n");
        stringBuilder.append("import com.my.drools.util.OutputDisplay\r\n");
        stringBuilder.append("import com.my.drools.entity.CashFlow\r\n");
        stringBuilder.append("import com.my.drools.entity.AccountingPeriod\r\n");
        stringBuilder.append("global OutputDisplay showResults;\r\n");
        stringBuilder.append("rule \""+rulename+"\"");
        stringBuilder.append("when\r\n");
        stringBuilder.append("Account()\r\n");
        stringBuilder.append("then\r\n");
        stringBuilder.append("showResults.show(\""+tip+"\");\r\n");
        stringBuilder.append("end\r\n");
        return stringBuilder.toString();
    }

    public static void insertKmodule() throws FileNotFoundException {
        File kmodule = ResourceUtils.getFile("classpath:META-INF/kmodule.xml");
        Document documentByFile = XmlUtil.getDocumentByFile(kmodule);
        Element rootElement = documentByFile.getRootElement();
        Element element = new DOMElement("kbase");
        element.addAttribute("name","rules4");
        element.addAttribute("packages","lesson4");
        element.add(new DOMElement("ksession").addAttribute("name","ksession-lesson4"));
        rootElement.add(element);
        XmlUtil.writeXML(documentByFile,kmodule);
    }
}
